//
//  ShoppingCartVC.swift
//  RPay
//
//  Created by Charlie Liao on 2017/6/27.
//  Copyright © 2017年 Charlie. All rights reserved.
//

import UIKit
import SnapKit

class ShoppingCartVC: BaseVC, UITableViewDataSource, UITableViewDelegate {
    
    // MARK: - Life Cycle
    override func loadView() {
        super.loadView()
        
        view.addSubview(tableView)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: "ShoppingCartCell", bundle: nil), forCellReuseIdentifier: "CellID")
        
        UINib(nibName: "CartBottomView", bundle: nil).instantiate(withOwner: self, options: nil)
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { (maker) in
            maker.left.bottom.right.equalToSuperview()
            maker.height.equalTo(48)
        }
        
        tableView.snp.makeConstraints { (maker) in
            maker.left.top.right.equalToSuperview()
            maker.bottom.equalTo(bottomView.snp.top)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = LocalStr("购物车")
        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tableView.reloadData()
        计算总价()
        allSelectBtn.isSelected = false
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        UserShare.shared.saveShoppingCart()
    }
    
    // MARK: - Table View Data Source
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return UserShare.shared.shoppingCart!.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellID", for: indexPath) as! ShoppingCartCell
        cell.goods = UserShare.shared.shoppingCart![indexPath.row]
        
        cell.tapDelete = { [weak self] (wCell: ShoppingCartCell, goods: GoodsModel) in
            let index = UserShare.shared.shoppingCart!.index(of: goods)
            if index != nil {
                UserShare.shared.removeFromCart(goods)
                self?.tableView.deleteRows(at: [IndexPath(row: index!, section: 0)], with: .automatic)
                UserShare.shared.saveShoppingCart()
                self?.计算总价()
            }
        }
        
        cell.amountDidChange = { [weak self] (wCell: ShoppingCartCell, goods: GoodsModel) in
            self?.计算总价()
        }
        
        return cell
    }
    
    // MARK: - Table View Delegate
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.cancelKeyBoard()
        
        let count: Int
        let indexPaths = tableView.indexPathsForSelectedRows
        if indexPaths != nil {
            count = indexPaths!.count
        } else {
            count = 0
        }
        
        allSelectBtn.isSelected = count == UserShare.shared.shoppingCart!.count
        计算总价()
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath)
    {
        tableView.cancelKeyBoard()
        allSelectBtn.isSelected = false
        计算总价()
    }
    
    // MARK: - Event respond
    /// 点击全选
    @IBAction func tapAllSelectBtn()
    {
        let flag = !allSelectBtn.isSelected
        for i in 0..<UserShare.shared.shoppingCart!.count {
            if flag {
                tableView.selectRow(at: IndexPath(row: i, section: 0), animated: true, scrollPosition: .none)
            } else {
                tableView.deselectRow(at: IndexPath(row: i, section: 0), animated: true)
            }
        }
        allSelectBtn.isSelected = flag
        计算总价()
    }
    
    /// 点击结算按钮
    @IBAction func tapSubimt()
    {
        var goodList = [GoodsModel]()
        let indexPaths = tableView.indexPathsForSelectedRows
        if indexPaths != nil {
            for indexPath in indexPaths! {
                let goods = UserShare.shared.shoppingCart![indexPath.row]
                goodList.append(goods)
            }
            
        } else {
            alert(LocalStr("你还没有选择商品哦"))
            return
        }
        
        let vc = ConfirmOrderVC()
        vc.list = goodList
        vc.hidesBottomBarWhenPushed = true
        navigationController!.pushViewController(vc, animated: true)
    }
    
    // MARK: - 私有方法
    ///
    private func 计算总价() {
        let indexPaths = tableView.indexPathsForSelectedRows
        var 合计: Double = 0
        if indexPaths != nil {
            for indexPath in indexPaths! {
                let goods = UserShare.shared.shoppingCart![indexPath.row]
                合计 = 合计+goods.price*Double(goods.num)
            }
        }
        合计Label.text = String(format: "%.2f", 合计)
    }
    
    // MARK: - Get / Set
    
    var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: .plain)
        tableView.rowHeight = 177
        tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 12.5))
        tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 12.5))
        tableView.separatorStyle = .none
        tableView.allowsMultipleSelection = true
        tableView.backgroundColor = UIColor.appBackground
        return tableView
    }()
    
    @IBOutlet var 合计Label: UILabel!
    @IBOutlet var bottomView: UIView!
    @IBOutlet weak var allSelectBtn: UIButton!
    
}
